<template>
  <div class="app-container">
    <el-form
      :model="queryParams"
      ref="queryRef"
      :inline="true"
      v-show="showSearch"
      label-width="68px"
    >
      <el-form-item label="饮用类型" prop="waterType">
        <el-select
          v-model="queryParams.waterType"
          placeholder="请选择饮用类型"
          clearable
        >
          <el-option
            v-for="dict in water_type"
            :key="dict.value"
            :label="dict.label"
            :value="dict.value"
          />
        </el-select>
      </el-form-item>
      <el-form-item label="录入时间" prop="createTime">
        <el-date-picker
          clearable
          v-model="queryParams.createTime"
          type="date"
          value-format="YYYY-MM-DD"
          placeholder="请选择录入时间"
        >
        </el-date-picker>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" icon="Search" @click="handleQuery"
          >搜索</el-button
        >
        <el-button icon="Refresh" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>

    <el-row :gutter="10" class="mb8" justify="space-between">
      <el-col :span="1.5">
        <el-button
          :type="buttonName == '新增' ? 'primary' : 'success'"
          plain
          icon="Plus"
          @click="handleAdd"
          v-hasPermi="['manage:drink:add']"
        >
          {{ buttonName }}
        </el-button>
        <el-button
          type="danger"
          plain
          icon="Delete"
          :disabled="multiple"
          @click="handleDelete"
          v-hasPermi="['manage:drink:remove']"
          >删除
        </el-button>
      </el-col>
      <el-col :span="1.5">
        <div style="display: flex">
          <div style="margin-right: 15px">
            <el-popover placement="right" :width="420" trigger="click">
              <template #reference>
                <div>
                  <el-tooltip content="点击查看今日饮水情况" placement="top">
                    <el-button circle>
                      <svg-icon icon-class="water-blue"></svg-icon>
                    </el-button>
                  </el-tooltip>
                </div>
              </template>
              <template #default>
                <div class="popover-content">
                  <el-empty v-if="todayDrinkInfo.totalTodayDrink === 0" description="今日暂未饮水" />
                  <div class="detail-row" v-if="todayDrinkInfo.totalTodayDrink !== 0">
                    <div class="detail-item">
                      <span class="label">今日总饮水量：</span>
                      <span class="value"
                        >{{ todayDrinkInfo.totalTodayDrink }} ml</span
                      >
                    </div>
                    <div class="detail-item">
                      <span class="label">今日总目标饮水量：</span>
                      <span class="value"
                        >{{ todayDrinkInfo.totalTargetDrink }} ml</span
                      >
                    </div>
                  </div>
                  <div
                    v-for="(row, rowIndex) in chunkedTodayVolumeByType"
                    :key="rowIndex"
                    class="detail-row"
                  >
                    <div
                      v-for="(volume, type) in row"
                      :key="type"
                      class="detail-item"
                    >
                      <span class="label" style="display: flex">
                        <dict-tag
                          :options="water_type"
                          :value="parseInt(type)"
                        />：
                      </span>
                      <span class="value">{{ volume }} ml</span>
                    </div>
                  </div>
                  <div class="detail-row" v-if="todayDrinkInfo.totalTodayDrink !== 0">
                    <div class="detail-item">
                      <span class="label">今日饮用最多：</span>
                      <span class="value" style="display: flex">
                        <dict-tag
                          :options="water_type"
                          :value="parseInt(todayDrinkInfo.mostConsumedWaterType)"
                          v-if="todayDrinkInfo.mostConsumedWaterType !== null"
                        />
                        <span v-else>暂无</span>
                      </span>
                    </div>
                  </div>
                  <div class="detail-row" v-if="todayDrinkInfo.totalTodayDrink !== 0">
                    <div class="detail-item suggestion-item">
                      <span class="label">建议：</span>
                      <span class="value">
                        <span v-if="todayDrinkInfo.mostConsumedWaterType == '3'"
                          >虽然饮茶对健康有益，但过量可能会影响睡眠和铁质吸收，建议适度饮用并关注自己的体验。</span
                        >
                        <span
                          v-else-if="
                            todayDrinkInfo.mostConsumedWaterType == '4'
                          "
                          >喝饮料过多可能导致糖分摄入过量和健康问题，建议适量饮用并多喝水。</span
                        >
                        <span
                          v-else-if="
                            todayDrinkInfo.mostConsumedWaterType == '5'
                          "
                          >饮酒过多可能对健康造成严重影响，建议适量饮酒。</span
                        >
                        <span v-else-if="todayDrinkInfo.totalTodayDrink === 0">今日暂未饮水。</span>
                        <span v-else>请继续保持。</span>
                      </span>
                    </div>
                  </div>
                </div>
              </template>
            </el-popover>
          </div>
          <right-toolbar
            v-model:showSearch="showSearch"
            @queryTable="getList"
          ></right-toolbar>
        </div>
      </el-col>
      <!-- <el-col :span="3">
        
      </el-col> -->
    </el-row>

    <el-table
      v-loading="loading"
      :data="drinkList"
      @selection-change="handleSelectionChange"
    >
      <el-table-column type="selection" width="55" align="center" />
      <el-table-column
        label="序号"
        type="index"
        align="center"
        prop="waterId"
        width=" 50"
      />
      <el-table-column label="今日饮用量" align="center" prop="todayDrink">
        <template #default="scope"> {{ scope.row.todayDrink }} ml </template>
      </el-table-column>
      <el-table-column label="目标饮用量" align="center" prop="targetDrink">
        <template #default="scope"> {{ scope.row.targetDrink }} ml </template>
      </el-table-column>
      <el-table-column
        label="饮用频率"
        align="center"
        prop="drinkFrequency"
        width="100"
      >
        <template #default="scope">
          {{ scope.row.drinkFrequency }} 次
        </template>
      </el-table-column>
      <el-table-column label="饮用类型" align="center" prop="waterType">
        <template #default="scope">
          <dict-tag :options="water_type" :value="scope.row.waterType" />
        </template>
      </el-table-column>
      <el-table-column
        label="是否达标"
        align="center"
        prop="isAchieved"
        width="100"
      >
        <template #default="scope">
          <el-tag v-if="checkDrink(scope.row)">已达标</el-tag>
          <el-tag v-else type="danger">未达标</el-tag>
        </template>
      </el-table-column>
      <el-table-column
        label="录入时间"
        align="center"
        prop="createTime"
        width="160"
        sortable
      >
        <template #default="scope">
          <span>{{
            parseTime(scope.row.createTime, "{y}-{m}-{d} {h}:{i}:{s}")
          }}</span>
        </template>
      </el-table-column>
      <el-table-column
        label="备注"
        align="center"
        prop="remark"
        width="250"
        show-overflow-tooltip
      />
      <el-table-column
        label="操作"
        align="center"
        class-name="small-padding fixed-width"
      >
        <template #default="scope">
          <!-- <el-button
            link
            type="primary"
            icon="Edit"
            @click="handleUpdate(scope.row)"
            v-hasPermi="['manage:drink:edit']"
            >修改</el-button
          > -->
          <el-button
            link
            type="danger"
            icon="Delete"
            @click="handleDelete(scope.row)"
            v-hasPermi="['manage:drink:remove']"
            >删除</el-button
          >
        </template>
      </el-table-column>
    </el-table>

    <pagination
      v-show="total > 0"
      :total="total"
      v-model:page="queryParams.pageNum"
      v-model:limit="queryParams.pageSize"
      @pagination="getList"
    />

    <!-- 添加或修改饮水记录对话框 -->
    <el-dialog :title="title" v-model="open" width="1000px" append-to-body>
      <el-form
        ref="drinkRef"
        :model="form"
        :rules="rules"
        label-width="auto"
        class="drinkTable"
      >
        <el-table :data="form.drinkList" style="width: 100%" :resizable="false">
          <!-- 使用 el-form-item 包裹每一列 -->
          <el-table-column label="今日饮用量" align="center" width="180">
            <template #default="scope">
              <el-form-item
                :prop="'drinkList.' + scope.$index + '.todayDrink'"
                :rules="rules.todayDrink"
              >
                <el-input-number
                  v-model="scope.row.todayDrink"
                  style="width: 80%"
                  :min="0"
                  :precision="0"
                  :step="1"
                />
                <span style="margin-left: 10px">ml</span>
              </el-form-item>
            </template>
          </el-table-column>

          <el-table-column label="目标饮用量" align="center" width="180">
            <template #default="scope">
              <el-form-item
                :prop="'drinkList.' + scope.$index + '.targetDrink'"
                :rules="rules.targetDrink"
              >
                <el-input-number
                  v-model="scope.row.targetDrink"
                  style="width: 80%"
                  :min="0"
                  :precision="0"
                  :step="1"
                />
                <span style="margin-left: 10px">ml</span>
              </el-form-item>
            </template>
          </el-table-column>

          <el-table-column label="饮用频率" align="center" width="180">
            <template #default="scope">
              <el-form-item
                :prop="'drinkList.' + scope.$index + '.drinkFrequency'"
                :rules="rules.drinkFrequency"
              >
                <el-input-number
                  v-model="scope.row.drinkFrequency"
                  style="width: 80%"
                  :min="0"
                  :precision="0"
                  :step="1"
                />
                <span style="margin-left: 10px">次</span>
              </el-form-item>
            </template>
          </el-table-column>

          <el-table-column label="饮用类型" align="center" width="140">
            <template #default="scope">
              <el-form-item
                :prop="'drinkList.' + scope.$index + '.waterType'"
                :rules="rules.waterType"
              >
                <el-select
                  v-model="scope.row.waterType"
                  placeholder="请选择类型"
                  clearable
                >
                  <el-option
                    v-for="dict in water_type"
                    :key="dict.value"
                    :label="dict.label"
                    :value="parseInt(dict.value)"
                  ></el-option>
                </el-select>
              </el-form-item>
            </template>
          </el-table-column>

          <el-table-column label="备注" align="center" width="180">
            <template #default="scope">
              <el-form-item :prop="'drinkList.' + scope.$index + '.remark'">
                <el-popover
                  placement="top-end"
                  :width="400"
                  trigger="manual"
                  :visible="scope.row.popoverVisible"
                >
                  <el-input
                    type="textarea"
                    :rows="4"
                    placeholder="请输入内容"
                    v-model="scope.row.remark"
                  />
                  <div style="text-align: right; margin-top: 8px">
                    <el-button size="small" @click="closePopover(scope.row)"
                      >取 消</el-button
                    >
                    <el-button
                      type="primary"
                      size="small"
                      @click="confirmEdit(scope.row)"
                      >确 定</el-button
                    >
                  </div>
                  <template #reference>
                    <el-input
                      v-model="scope.row.remark"
                      placeholder="请输入备注"
                      @click="openPopover(scope.row)"
                    >
                    </el-input>
                  </template>
                </el-popover>
              </el-form-item>
            </template>
          </el-table-column>

          <el-table-column label="操作" width="100" align="center">
            <template #default="scope">
              <el-button
                link
                type="danger"
                icon="Delete"
                @click="handleRemoveItem(scope.$index)"
                >删除</el-button
              >
            </template>
          </el-table-column>
        </el-table>
        <div style="display: flex; justify-content: center; margin-top: 10px">
          <el-button
            plain
            icon="CirclePlus"
            link
            type="primary"
            @click="handleAddItem"
            >新增</el-button
          >
        </div>
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button type="primary" @click="submitForm">确 定</el-button>
          <el-button @click="cancel">取 消</el-button>
        </div>
      </template>
    </el-dialog>
  </div>
</template>

<script setup name="Drink">
import { listDrink, getDrink, delDrink, addDrink, updateDrink } from "@/api/manage/drink"

const { proxy } = getCurrentInstance()
const { water_type } = proxy.useDict('water_type')

const drinkList = ref([])
const open = ref(false)
const loading = ref(true)
const showSearch = ref(true)
const ids = ref([])
const single = ref(true)
const multiple = ref(true)
const total = ref(0)
const title = ref("")
const drinkFormList = ref([])
const buttonName = ref("新增")

const data = reactive({
  form: {
    drinkList: []
  },
  queryParams: {
    pageNum: 1,
    pageSize: 10,
    waterType: null,
    createTime: null,
  },
  rules: {
    todayDrink: [
      { required: true, message: "今日饮水量不能为空", trigger: "blur" }
    ],
    targetDrink: [
      { required: true, message: "目标饮水量不能为空", trigger: "blur" }
    ],
    drinkFrequency: [
      { required: true, message: "饮水频率不能为空", trigger: "blur" }
    ],
    waterType: [
      { required: true, message: "饮水类型不能为空", trigger: "change" }
    ],
  }
})

const { queryParams, form, rules } = toRefs(data)

const todayDrinkInfo = ref({})

// 监听 form 中的三个列表的变化
watch(() => [drinkFormList.value.length], ([drinkListLength]) => {
  if (drinkListLength > 0) {
    buttonName.value = "修改"
    title.value = "修改饮水记录"
  } else {
    buttonName.value = "新增"
    title.value = "新增饮水记录"
  }
  console.log(drinkFormList.value)
}, { immediate: true })

/** 查询饮水记录列表 */
function getList () {
  loading.value = true
  listDrink(queryParams.value).then(response => {
    drinkList.value = response.rows
    total.value = response.total
    loading.value = false
  })
  getFormDrinkList()
}

function getFormDrinkList () {
  const now = new Date()
  const data = {}
  data.createTime = now.getFullYear() + "-" + (now.getMonth() + 1) + "-" + now.getDate()
  listDrink(data).then(response => {
    drinkFormList.value = response.rows
    getTodayDrinkInfo(drinkFormList)
  })

  const getTodayDrinkInfo = (drinkDataList) => {
    let totalTodayDrink = 0
    let totalTargetDrink = 0
    const targetVolumeByType = {}
    const todayVolumeByType = {}

    drinkDataList.value.forEach(item => {
      totalTodayDrink += item.todayDrink
      totalTargetDrink += item.targetDrink

      if (!targetVolumeByType[item.waterType]) {
        targetVolumeByType[item.waterType] = 0
      }
      targetVolumeByType[item.waterType] += item.targetDrink

      if (!todayVolumeByType[item.waterType]) {
        todayVolumeByType[item.waterType] = 0
      }
      todayVolumeByType[item.waterType] += item.todayDrink
    })

    // 找出饮用量最多的waterType
    let maxWaterTypeByVolume = null
    let maxVolume = 0
    for (const [type, volume] of Object.entries(todayVolumeByType)) {
      if (volume > maxVolume) {
        maxVolume = volume
        maxWaterTypeByVolume = type
      }
    }

    todayDrinkInfo.value.totalTodayDrink = totalTodayDrink
    todayDrinkInfo.value.totalTargetDrink = totalTargetDrink
    todayDrinkInfo.value.targetVolumeByType = targetVolumeByType
    todayDrinkInfo.value.todayVolumeByType = todayVolumeByType
    todayDrinkInfo.value.mostConsumedWaterType = maxWaterTypeByVolume
    console.log("水滴数据", todayDrinkInfo.value)
  }
}

const chunkedTodayVolumeByType = computed(() => {
  if (todayDrinkInfo.value.todayVolumeByType) {
    const items = Object.entries(todayDrinkInfo.value.todayVolumeByType)
    const chunkSize = 2
    const chunks = []
    for (let i = 0; i < items.length; i += chunkSize) {
      chunks.push(Object.fromEntries(items.slice(i, i + chunkSize)))
    }
    return chunks
  }
})

// 取消按钮
function cancel () {
  open.value = false
  reset()
}

// waterId: null,
// todayDrink: null,
// targetDrink: null,
// drinkFrequency: null,
// waterType: null,
// userId: null,
// createTime: null,
// remark: null,

// 表单重置
function reset () {
  form.value = {
    drinkList: []
  }
  proxy.resetForm("drinkRef")
}

/** 搜索按钮操作 */
function handleQuery () {
  queryParams.value.pageNum = 1
  getList()
}

/** 重置按钮操作 */
function resetQuery () {
  proxy.resetForm("queryRef")
  handleQuery()
}

// 多选框选中数据
function handleSelectionChange (selection) {
  ids.value = selection.map(item => item.waterId)
  single.value = selection.length != 1
  multiple.value = !selection.length
}

/** 新增按钮操作 */
function handleAdd () {
  reset()
  getFormDrinkList()
  form.value.drinkList = [...drinkFormList.value]
  open.value = true
  title.value = "添加饮水记录"
}

/** 修改按钮操作 */
function handleUpdate (row) {
  reset()
  const _waterId = row.waterId || ids.value
  getDrink(_waterId).then(response => {
    form.value = response.data
    open.value = true
    title.value = "修改饮水记录"
  })
}

/** 提交按钮 */
function submitForm () {
  // 检查form.value.drinkList中的每个元素的water_id是否为空
  const isUpdate = form.value.drinkList.some(drink => drink.waterId !== null && drink.waterId !== undefined)
  proxy.$refs["drinkRef"].validate(valid => {
    if (valid) {
      if (isUpdate) {
        if (checkWaterType(form.value.drinkList)) {
          updateDrink(form.value.drinkList).then(response => {
            proxy.$modal.msgSuccess("修改成功")
            open.value = false
            getList()
          })
        } else {
          proxy.$modal.msgError("您填写了重复的饮水类型，请将其合并")
        }
      } else {
        if (checkWaterType(form.value.drinkList)) {
          addDrink(form.value.drinkList).then(response => {
            proxy.$modal.msgSuccess("新增成功")
            open.value = false
            getList()
          })
        } else {
          proxy.$modal.msgError("您填写了重复的饮水类型，请将其合并")
        }
      }
    } else {
      // 给用户提示
      proxy.$modal.msgError("请填写必填项")
    }
  })
}

/** 删除按钮操作 */
function handleDelete (row) {
  const _waterIds = row.waterId || ids.value
  const delName = _waterIds.length >= 1 ? '选中的饮水记录' : '这条饮水记录'
  proxy.$modal.confirm('确定要删除' + delName + '吗？').then(function () {
    return delDrink(_waterIds)
  }).then(() => {
    getList()
    // getFormDrinkList()
    proxy.$modal.msgSuccess("删除成功")
  }).catch(() => { })
}

/** 导出按钮操作 */
function handleExport () {
  proxy.download('manage/drink/export', {
    ...queryParams.value
  }, `drink_${new Date().getTime()}.xlsx`)
}

// 计算饮水量是否达到目标
const checkDrink = (row) => {
  const _todayDrink = row.todayDrink
  const _targetDrink = row.targetDrink
  if (_todayDrink >= _targetDrink) {
    return true
  } else {
    return false
  }
}

// 新增饮水记录
function handleAddItem () {
  form.value.drinkList.push({})
}

// ���除饮水记录
function handleRemoveItem (index) {
  form.value.drinkList.splice(index, 1)
}

// 打开 Popover
function openPopover (row) {
  if (!row.popoverVisible) {  // 防止重复打开
    row.popoverVisible = true
  }
};

function confirmEdit (row) {
  row.popoverVisible = false
};

// 关闭 Popover
function closePopover (row) {
  row.popoverVisible = false
  row.remark = null  // 清除输入内容
};

// 校验drinkList中的数据waterType是否有重复的，如果有，给用户弹出提示
function checkWaterType (drinkList) {
  const waterTypeSet = new Set(drinkList.map(item => item.waterType))
  if (waterTypeSet.size !== drinkList.length) {
    return false
  }
  return true
}

getList()
getFormDrinkList();
</script>

<style scoped>
.drinkTable .el-form-item {
  margin-bottom: 0 !important;
}

.popover-content {
  padding: 10px;
}

.detail-row {
  display: flex;
  justify-content: space-between;
  margin-bottom: 5px;
}

.detail-item {
  display: flex;
  align-items: center;
  width: 50%;
}

.label {
  font-weight: bold;
  width: auto;
}

.value {
  width: auto;
  white-space: normal; /* 确保文本可以自动换行 */
}

.suggestion-item {
  width: 100% !important;
  align-items: flex-start !important;
}

.suggestion-item .label {
  width: auto;
  margin-right: 8px;
  flex-shrink: 0;
}

.suggestion-item .value {
  flex: 1;
  line-height: 1.5;
}
</style>
